package com.lanswon.qzsmk.controller.cardManageController;


import java.util.HashMap;
import java.util.Map;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.exception.UserException;
import com.lanswon.qzsmk.model.ActiveUser;
import com.lanswon.qzsmk.service.systemManageService.TellerManageService;
import com.lanswon.qzsmk.util.JudgeBrowser;
import com.lanswon.qzsmk.vo.SaveOrUpdateTellerVo;

@Controller
public class LoginController  {
	private static Logger logger = (Logger) LoggerFactory.getLogger(LoginController.class);

	@Autowired
	TellerManageService tms;

	
	/**
	 * 链接系统主页
	 * @return
	 */
	@RequestMapping(name="系统主页",value={"/index.html"},method=RequestMethod.GET)
	public String longin(HttpServletRequest request){	

        logger.debug(request.getSession().getAttribute("activeUser").toString()+"----------------");
        
		return "index";
	}
	
	/**
	 * 系统主页获取用户信息
	 * @param request
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/getActiveUser",method=RequestMethod.POST)
	@ResponseBody
	public SaveOrUpdateTellerVo getActiveUser(HttpServletRequest request) throws Exception{
		ActiveUser activeUser=(ActiveUser) request.getSession().getAttribute("activeUser");
		
		return tms.queryUserByUserNo(activeUser.getUserNo());
	}
	
	/**
	 * 修改密码时，检查原密码是否正确
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/checkOldPassword",method=RequestMethod.POST)
	@ResponseBody
	public boolean checkOldPassword(int userNo,String oldPassword) throws Exception{
		SaveOrUpdateTellerVo vo = tms.queryUserByUserNo(userNo);
		
		 ByteSource credentialsSalt = ByteSource.Util.bytes(vo.getLoginName());
		
		 Object result = new SimpleHash("MD5",oldPassword,credentialsSalt,1024); 
		 oldPassword =  result.toString();
		 if(vo.getLoginPassword().equals(oldPassword))
			 return true;
		 
		return false;
	}
	
	
	/**
	 * 链接修改密码页面
	 * @return
	 */
	@RequestMapping(value="/goUpdateWordPass",method=RequestMethod.GET)
	public String goUpdateWordPass(){
		return "UpdatePassWord";
	}
	
	/**
	 * 修改密码提交
	 * @param tellerVo
	 * @return
	 */
	@RequestMapping(value="/updatepassWord",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> updatepassWord(SaveOrUpdateTellerVo tellerVo){
		Map<String, Object> map=new HashMap<>();
		tms.modifyTellerPassWord(tellerVo);
		map.put("statusCode", "200");
		map.put("message", "操作成功");
		map.put("callbackType", "closeCurrent");
		return map;
	}
	
	@RequestMapping(value="/refuse.html",method=RequestMethod.GET)
	public String refuse(){
		return "Refuse";
	}
	
	 @RequestMapping(value = "/login.htm", method = RequestMethod.GET)
	 	//2019/1/18 hgl 以下8行
	    public String showLoginPage(HttpServletRequest request) {
		 String agent=request.getHeader("User-Agent").toLowerCase();
		 String browserName = JudgeBrowser.getBrowserName(agent);
		 logger.debug("browserName==>"+browserName);
		 if("ie11".equals(browserName)||"ie10".equals(browserName)){
			 return "/login"; 
		 }else{
			 return "BrowserErrorPage";
		 }
	    }

	
	
	@RequestMapping(value = "/login.htm",method=RequestMethod.POST)  
	    public String login(HttpServletRequest request)    { 
		 
		 HttpSession session=request.getSession();
	        //shiro在认证通过后出现错误后将异常类路径通过request返回  
	        //如果登陆失败从request中获取认证异常信息，shiroLoginFailure就是shiro异常类的全限定名  
	        String exceptionClassName = (String)request.getAttribute("shiroLoginFailure");  
	        System.out.println("exceptionClassName:"+exceptionClassName);
//	        try{
		        if (exceptionClassName!=null) {  
		            if (UnknownAccountException.class.getName().equals(exceptionClassName)) {  
		            	UserException userException= new UserException(ErrorCode.USER_NOT_EXIST,"账号不存在");
		            	 session.setAttribute("error", userException);
		            } else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)){  
		            	UserException userException= new UserException(ErrorCode.LOGIN_PWD_ERROR,"密码错误");		
		            	 session.setAttribute("error", userException);
		            }else if(LockedAccountException.class.getName().equals(exceptionClassName)) {
		            	System.out.println(exceptionClassName);
		            	UserException userException= new UserException(ErrorCode.USER_NOT_BRANCH,"用户未绑定网点");		
		            	 session.setAttribute("error", userException);
					}		           
		        }else if(exceptionClassName==null){
		        	return "redirect:/index.html";
		        }
		        return "login";
	    }
	 
	 /**
	  * 获取登陆页面的异常
	  * @param request
	  * @return
	  */
	 @ResponseBody
	 @RequestMapping(value="/getLoginException",method=RequestMethod.POST)
	 public UserException getLoginException(HttpServletRequest request){
		 UserException userException=(UserException) request.getSession().getAttribute("error");
		 request.getSession().removeAttribute("error");
		 return userException;
	 }

}

